
//
// 120315 - AH - (Bergen Off. Bibliotek) Created.
//

package org.soekrat.engine.io;

import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import org.soekrat.AttributeObject;

/**
 * <p>
 *   Utilities methods of use when serializing 
 *   {@link AttributeObject}s to XML.
 * </p>
 * @author Arne Halvorsen
 * @author Laetitia Le Chatton
 */
public final class AttributeObjectXml 
{
  private final Set<String> m_ignore=new HashSet<String>();
  
  /**
   * <p>
   *   Construction.
   * </p>
   */
  public AttributeObjectXml(){}
  
  /**
   * <p>
   *   Sets attribute to ignore when writing XML.
   * </p>
   * @param name Name on attribute to ignore.
   * @return {@code this}.
   */
  public AttributeObjectXml ignoreAttribute(String name)
  { 
    m_ignore.add(name);
    return this;
  }
  
  /**
   * <p>
   *   Prints the part of XML that is the name/value attribute pairs.
   * </p>
   * @param ao {@link AttributeObject} being serialized to XML.
   * @param pw Stream to print to.
   */
  public void toXml(AttributeObject ao, PrintWriter pw)
  {
    if (ao==null)
    {
      throw new NullPointerException("ao");
    }
    if (pw==null)
    {
      throw new NullPointerException("pw");
    }
    
    StringBuilder sb=new StringBuilder();
    String[] names=ao.getAttributeNames();
    for (String name : names) 
    {
      if (!m_ignore.contains(name))
      {
        Object value=ao.getAttribute(name);
        if (value!=null)
        {
          sb.append("  <attribute name='").append(name).append("' value='")
            .append(value.toString()).append("' />");
        }
      }
    }
  }
  
}
